package com.example.xinhuazidian.base

import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.xinhuazidian.utils.ActivityCollector

abstract class BaseActivity<P : BasePresenter<*>?> : AppCompatActivity(), BaseView {
    var context: Context? = null
    var toast: Toast? = null
    protected var presenter: P? = null
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            //当isShouldHideInput(v, ev)为true时，表示的是点击输入框区域，则需要显示键盘，
            //同时显示光标，反之，需要隐藏键盘、光标
            if (isShouldHideInput(v, ev)) {
                //处理Editext的光标隐藏、显示逻辑
                closeKeybord(v as EditText?, this)
            }
            return super.dispatchTouchEvent(ev)
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }

    /**
     * 判断点击的区域是否EditText之外
     * @return 返回true说明点击的是输入框区域外
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v is EditText) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            // 点击的是输入框区域，保留点击EditText的事件
            return (event.x <= left || event.x >= right
                    || event.y <= top || event.y >= bottom)
        }
        return false
    }

    protected abstract fun createPresenter(): P
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
        presenter = createPresenter()
        //onCreate中增加Activity到任务管理器
        ActivityCollector.addActivity(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (presenter != null) {
            presenter!!.detachView()
        }
    }

    companion object {
        /**
         * 关闭软键盘的方法（写在 KeyBoardUtils 的工具类里面）
         *
         * @param mEditText 输入框
         * @param mContext  上下文
         */
        fun closeKeybord(mEditText: EditText?, mContext: Context?) {
            if (mEditText != null && mContext != null) {
                val imm = mContext
                    .getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(mEditText.windowToken, 0)
            }
        }
    }
}